from random import randint
# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code
from users.models import User
from users.serializer import UserSerialzier, UserDetailSerializer, UserEmailSerialzier, PasswordChange


class SMSCodeView(APIView):
    def get(self, request, mobile):
        # 0.60秒内不允许重复发短信
        conn = get_redis_connection("sms_code")
        flag = conn.get("sms_code_flag%s" % mobile)
        if flag:
            return Response({"error": "请求过于频繁"}, status=status.HTTP_403_FORBIDDEN)

        # 1.从路由中获取手机号码
        # 2.生成短信验证码
        sms_code = "%04d" % randint(0, 9999)
        # 3.将短信验证码保存到redis缓存中
        # 3.1.使用管道对象，将两个存储一次性执行
        pl = conn.pipeline()
        pl.setex("sms_code_%s" % mobile, 60 * 5, sms_code)  # key,timeout,value
        pl.setex("sms_code_flag%s" % mobile, 60, sms_code)  # 超时flag
        # 3.2.#执行命令
        pl.execute()
        # 4.发送短信

        try:
            print("准备发送")
            send_sms_code.delay(mobile, sms_code, 5)
        except Exception as e:
            print("短信出错")
        # ccp.send_template_sms('13051528719', ['1234', 5], 1)
        # 5.返回结果
        return Response({"message": "OK"})


class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }

        return Response(data)


class MobilesCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data)


class UserView(CreateAPIView):
    """
        注册保存信息
    """
    serializer_class = UserSerialzier


class UserDetailView(RetrieveAPIView):

    queryset = User.objects.all()

    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user

class UserEmailView(UpdateAPIView):

    serializer_class = UserEmailSerialzier
    # queryset = User.objects.all()

    #序列化前获取 user 对应信息
    def get_object(self):
        return self.request.user

class UserEmaiverifylView(APIView):

    def get(self,request):

        # 获取token
        token = request.query_params.get("token")
        if not token:
            return Response({"error":"邮箱链接参数缺少token"},status=status.HTTP_400_BAD_REQUEST)

        # 验证用户

        user = User.check_verify_email_token(token)

        if user is None:
            return Response({"error":"链接无效"},status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()

        return Response({"message":"OK"},status=status.HTTP_200_OK)


class UserPasswordChange(UpdateAPIView):
    serializer_class = PasswordChange

    def get_object(self):
        #print(self.request.user.email)
        return self.request.user











